package com.example.logindb.sevices;

import com.example.logindb.dto.UserDTO;
import com.example.logindb.entity.Location;
import com.example.logindb.entity.Online;
import com.example.logindb.entity.User;
import com.example.logindb.repository.LocationRepository;
import com.example.logindb.repository.OnlineRepository;
import com.example.logindb.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    private UserRepository userRepository;
    private PasswordEncoder passwordEncoder;
    private LocationRepository locationRepository;
    private OnlineRepository onlineRepository;
    public UserServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder, LocationRepository locationRepository, OnlineRepository onlineRepository) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
        this.locationRepository = locationRepository;
        this.onlineRepository = onlineRepository;
    }
    //    public UserServiceImpl(UserRepository userRepository,PasswordEncoder passwordEncoder                           ) {
//    this.userRepository = userRepository;
//    this.passwordEncoder = passwordEncoder;
//}
    //web
    @Override
    public void saveUser(UserDTO userDTO) {
        User user = new User();
        user.setName(userDTO.getName());
        user.setUsername(userDTO.getUsername());
        user.setRole("USER");
        user.setUserrole(userDTO.getUserrole());
        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        // user.setPassword(userDTO.getPassword());
        userRepository.save(user);
        if(user.getUserrole().equals("blind"))
        {
            int save_id=user.getId();
            String filepath="";
            File directory = new File(filepath+save_id);
            if (!directory.exists()) {
                if (directory.mkdir()) {
                    System.out.println("文件夹创建成功！");
                } else {
                    System.out.println("文件夹创建失败！");
                }
            } else {
                System.out.println("文件夹已存在！");
            }
        }
    }


    @Override
    public void updateUser(UserDTO userDTO) {
        User existing = userRepository.findAllById( userDTO.getId() );
        existing.setName(userDTO.getName());
        existing.setUsername(userDTO.getUsername());
        userRepository.save(existing);
    }

    @Override
    public void deleteUserById(int id) {
        userRepository.deleteById(id);
    }

    @Override
    public User findByUsername(String email) {
        return userRepository.findByUsername(email);
    }

    @Override
    public UserDTO findById(int id) {
        User existingUser =  userRepository.findAllById(id);
        if(existingUser == null)
            return null;
        UserDTO userDTO = new UserDTO();
        userDTO.setId(existingUser.getId());
        userDTO.setUsername(existingUser.getUsername());
        userDTO.setUserrole(existingUser.getUserrole());
        userDTO.setName(existingUser.getName());
        userDTO.setPassword(existingUser.getPassword());
        return userDTO;
    }

    @Override
    public List<UserDTO> findAllByRole(String role) {
        List<User> users = userRepository.findAllByRole(role);
        return  users.stream()
//                .map( user -> convertUserToDto(user))
                .map(this::convertUserToDto)
                .collect(Collectors.toList());
    }


    @Override
    public List<UserDTO> searchUser(String role, String name) {
        List<User> users = userRepository.findAllByRoleAndNameStartingWithIgnoreCase(role,name);
        return users.stream()
//                .map((user) -> convertUserToDto(user))
                .map(this::convertUserToDto)
                .collect(Collectors.toList());
    }


    //  Helping method for findAllByRole() and searchUser()
    private UserDTO convertUserToDto(User user) {
        UserDTO userDto = new UserDTO();
        userDto.setId(user.getId());
        userDto.setName(user.getName());
        userDto.setUsername(user.getUsername());
        userDto.setRole(user.getRole());
        return userDto;
    }

    @Override
    public boolean isExists(String phone){
        return userRepository.existsByUsername(phone);
    }

    @Override
    public User getUserbyphone(String userPhone) {
        return userRepository.findByUsername(userPhone);
    }

    @Override
    public User edit(UserDTO user) {
        User usernew=new User();
        BeanUtils.copyProperties(user,usernew);
        return userRepository.save(usernew);
    }

    @Override
    public int countByUserrole(String role) {
        return userRepository.countByUserrole(role);
    }

    @Override
    public List<User> findUsersByBlindids(List<Integer> blindids) {
        return userRepository.findAllByIdIn(blindids);
    }

    @Override
    public User getUser(Integer userId) {
        return userRepository.findAllById(userId);
    }

    @Override
    public Optional<User> ifpresent(int gId) {
        return userRepository.findById(gId);
    }

    @Override
    public Integer blindNumber(String blind) {
        return userRepository.countByUserrole(blind);
    }

    @Override
    public List<Map<String, Object>> getUserLocations() {
        List<Location> locations = locationRepository.findAll();
        List<Map<String, Object>> result = new ArrayList<>();

        for (Location location : locations) {
            Online onlineStatus = onlineRepository.findById(location.getLocid());//id对应在线状态
            User userInfo = userRepository.findAllById(location.getLocid());

            Map<String, Object> userLocation = new HashMap<>();
            userLocation.put("latitude", location.getLat());
            userLocation.put("longitude", location.getLon());
            userLocation.put("userId", location.getLocid());
            userLocation.put("status", onlineStatus.getStatus());
            userLocation.put("name", userInfo != null ? userInfo.getName() : null);
            userLocation.put("phone", userInfo != null ? userInfo.getUsername() : null);

            result.add(userLocation);
        }
        return result;
    }

    @Override
    public Page<User> searchUser2(String user, String name, Pageable pageable) {
        return userRepository.findByRoleAndUsernameContaining(user, name, pageable);

    }

    @Override
    public User findAllById(int id) {
        return userRepository.findAllById(id);
    }

    @Override
    public Page<User> searchBlinds(Pageable pageable) {
        return userRepository.findAllByUserrole("blind", pageable);
    }

    @Override
    public Page<User> searchVolunterrs(Pageable pageable) {
        return userRepository.findAllByUserrole("volunteer", pageable);
    }

    @Override
    public Page<User> searchGuardians(Pageable pageable) {
        return userRepository.findAllByUserrole("guardian", pageable);
    }

    @Override
    public Object getCount() {
        return userRepository.count();
    }

//    @Override
//    public PageInfo<User> selectAll(String name, int pageNum, int i) {
//        PageInfo<User> pageInfo = null;
//        //告诉分页组件，你需要显示的页码和每页显示的条数
//        //PageHelper.startPage(pageNum,i);
//        //查询所有的用户信息
//        List<User> list = userRepository.findAllByName(name);
//        pageInfo = new PageInfo<>(list,i);
//        return pageInfo;
//
//    }


}
